# encoding: utf-8


import os
import glob
import shutil
import time
import os
import re
from framework.utils.TimeUtil import *

class DirUtil:
    def __init__(self):
        pass

    @classmethod
    def renameLastFileByXls(cls,dirname):
        #  获取source_dir 目录下全部图片，包含子文件夹
        xlslist = glob.glob(dirname + '*.xls', recursive=True)
        while(len(xlslist) == 0):
            time.sleep(1)
            xlslist = glob.glob(dirname + '*.xls', recursive=True)

        # 获取最新的图片
        latest_xls = max(xlslist, key=os.path.getctime)
        os.rename(latest_xls, dirname + "11.xls")
        return dirname + "11.xls"

    @classmethod
    def renameNewLastFileByXls(cls,dirname,reg,newname,type=".xls"):
        #  获取source_dir 目录下全部图片，包含子文件夹
        xlslist = glob.glob(dirname + '*' + reg + '*' + type, recursive=True)
        cnt = 0
        while(len(xlslist) == 0 and cnt < 20):
            time.sleep(1)
            cnt += 1
            xlslist = glob.glob(dirname + '*' + reg + '*' + type, recursive=True)
        try:
            # 获取最新的图片
            latest_xls = max(xlslist, key=os.path.getctime)
            time.sleep(2)
            os.rename(latest_xls, dirname + newname + type)
        except (PermissionError,ValueError):
            print(dirname + newname + type + "文件生成失败")
            return False
        return dirname + newname + type

    @classmethod
    def deleteByDir(cls,dir,type=""):
        for files in os.listdir(dir):
            if type != "":
                if files.endswith(".py"):
                    os.remove(os.path.join(dir, files))
            else:
                os.remove(os.path.join(dir, files))

    @classmethod
    def getLastFile(cls,dirname,type="*.xls"):
        xlslist = glob.glob(dirname + type, recursive=True)
        print(xlslist)
        latest_xls = ''
        if len(xlslist) > 0:
            latest_xls = max(xlslist, key=os.path.getctime)
        return latest_xls

    @classmethod
    def matchFile(cls,dirname,type="*.xls"):
        filename = cls.getLastFile(dirname,type)
        filename_arr = filename.split("\\")
        name = filename_arr[len(filename_arr)-1]
        #reg = re.compile("[A-Za-z0-9\_]", re.S)  # 增加匹配效率的 S 多行匹配
        reg = re.compile("[0-9]", re.S)  # 增加匹配效率的 S 多行匹配
        Lists = re.findall(reg, str(name))
        tmp_name = "".join(Lists)
        file_time = tmp_name[:14]
        cur_time = TimeUtil.getStartAndEnd(2,"%Y%m%d%H%M%S")[0]
        if file_time >= cur_time:
            return filename
        else:
            return filename
    @classmethod
    def copy_file(cls,oldpath,newpath):
        shutil.copy(oldpath,newpath)



